<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Admin extends CI_Controller {

    public $data;

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        if (!$this->session->userdata('loggedin')) {
            redirect('/sessions/login');
        }
        $this->load->database();
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $this->data['userdata'] = $this->session->userdata('data');
    }

    public function index() {
        $this->load->library('session');
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
        $this->load->view('admin/footer.php');
    }

    public function usuarios() {
        $this->load->view('admin/header.php');
        print_r( $this->data);
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
        try {
            $crud = new grocery_CRUD();
            $crud->set_field_upload('foto', 'assets/uploads/files');
            $crud->set_language("spanish");
            $crud->set_theme('flexigrid');
            $crud->set_table('users');
            $crud->set_subject('Usuarios');

            $crud->set_relation('role_id', 'roles', 'rol');

            $crud->required_fields('email', 'nombre', 'telefono', 'apellido', 'role_id');
            $crud->change_field_type('password', 'password');

            $crud->callback_before_insert(array($this, 'encrypt_password_callback'));
            $crud->callback_before_update(array($this, 'encrypt_password_callback'));
            $crud->callback_edit_field('password', array($this, 'change_input_to_button'));
            $crud->callback_add_field('password', array($this, 'set_password_input_to_empty'));

            $crud->columns('id', 'email', 'nombre', 'apellido', 'telefono');

            $output = $crud->render();
            $this->output('admin/usuarios/abm.php', $output);
        } catch (Exception $e) {
            show_error($e->getMessage() . ' --- ' . $e->getTraceAsString());
        }
        $this->load->view('admin/footer.php');
    }

    public function roles() {
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
        try {
            $crud = new grocery_CRUD();
            $crud->set_language("spanish");
            $crud->set_theme('flexigrid');
            $crud->set_table('roles');
            $crud->set_subject('Roles');



            $output = $crud->render();
            $this->output('admin/usuarios/abm.php', $output);
        } catch (Exception $e) {
            show_error($e->getMessage() . ' --- ' . $e->getTraceAsString());
        }
        $this->load->view('admin/footer.php');
    }

    public function courses2() {
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
        try {
            $crud = new grocery_CRUD();
            $crud->set_field_upload('photo', 'assets/uploads/files');
            $crud->set_language("spanish");
            $crud->set_theme('flexigrid');
            $crud->set_table('courses');
            $crud->set_subject('Cursos');

            $crud->set_relation('subcategory_id', 'subcategories', 'name');
            $crud->set_relation('institute_id', 'institutes', 'name');
            $crud->set_relation('mode_id', 'modes', 'name');
            $crud->set_relation('currency_id', 'currencies', '{name} ({symbol})');

            $crud->display_as('name', 'Nombre');
            $crud->display_as('description', 'Descripcion');
            $crud->display_as('subcategory_id', 'Subcategoria');
            $crud->display_as('institute_id', 'Instituto');
            $crud->display_as('date_start', 'Fecha Inicio');
            $crud->display_as('date_end', 'Fecha Fin');
            $crud->display_as('mode_id', 'Modalidad');
            $crud->display_as('title', 'Titulo');
            $crud->display_as('price', 'Precio');
            $crud->display_as('pay_period', 'Periodo de Pago');
            $crud->display_as('featured', 'Destacado');
            $crud->display_as('duration', 'Duracion');
            $crud->display_as('photo', 'Foto');
            $crud->display_as('currency_id', 'Moneda');
            $crud->display_as('status', 'Estado');

            $crud->columns('name', 'subcategory_id', 'mode_id', 'price', 'status');


            //$crud->required_fields('password','email', 'nombre', 'telefono', 'apellido');
            //$crud->change_field_type('password', 'password');
            //$crud->callback_before_insert(array($this, 'encrypt_password_callback'));
            //$crud->callback_before_update(array($this, 'encrypt_password_callback'));
            //$crud->callback_edit_field('password', array($this,'change_input_to_button'));
            //$crud->callback_add_field('password', array($this,'set_password_input_to_empty'));
            //$crud->columns('id','email','nombre','apellido','telefono');

            $output = $crud->render();
            $this->output('admin/usuarios/abm.php', $output);
        } catch (Exception $e) {
            show_error($e->getMessage() . ' --- ' . $e->getTraceAsString());
        }
        $this->load->view('admin/footer.php');
    }

    public function course_contacts() {
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
        try {
            $crud = new grocery_CRUD();

            //$crud->set_language("spanish");
            //$crud->set_theme('flexigrid');
            $crud->set_table('course_contacts');
            $crud->set_subject('Contactos');

            $crud->set_relation('course_id', 'courses', 'name');

            $crud->display_as('name', 'Nombre');
            $crud->display_as('phone', 'Telefono');
            $crud->display_as('query', 'Consulta');
            $crud->display_as('course_id', 'Curso');
            $crud->display_as('date_time', 'Fecha');

            //$crud->field_type('date_time','date');
            //$crud->required_fields('password','email', 'nombre', 'telefono', 'apellido');
            //$crud->change_field_type('password', 'password');
            //$crud->callback_before_insert(array($this, 'encrypt_password_callback'));
            //$crud->callback_before_update(array($this, 'encrypt_password_callback'));
            //$crud->callback_edit_field('password', array($this,'change_input_to_button'));
            //$crud->callback_add_field('password', array($this,'set_password_input_to_empty'));
            //$crud->columns('id','email','nombre','apellido','telefono');

            $output = $crud->render();
            $this->output('admin/usuarios/abm.php', $output);
        } catch (Exception $e) {
            show_error($e->getMessage() . ' --- ' . $e->getTraceAsString());
        }
        $this->load->view('admin/footer.php');
    }

    public function institutes() {
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
        try {
            $crud = new grocery_CRUD();
            $crud->set_field_upload('photo', 'public/images/instituciones');
            $crud->set_language("spanish");
            $crud->set_theme('flexigrid');
            $crud->set_table('institutes');
            $crud->set_subject('Instituciones');

            $crud->set_relation('city_id', 'cities', 'name');

            $crud->display_as('name', 'Nombre');
            $crud->display_as('address', 'Direccion');
            $crud->display_as('phone', 'Telefono');
            $crud->display_as('photo', 'Foto');
            $crud->display_as('city_id', 'Ciudad');
            $crud->display_as('sstatus', 'Estado');

            //$crud->required_fields('password','email', 'nombre', 'telefono', 'apellido');
            //$crud->change_field_type('password', 'password');
            //$crud->callback_before_insert(array($this, 'encrypt_password_callback'));
            //$crud->callback_before_update(array($this, 'encrypt_password_callback'));
            //$crud->callback_edit_field('password', array($this,'change_input_to_button'));
            //$crud->callback_add_field('password', array($this,'set_password_input_to_empty'));
            //$crud->columns('id','email','nombre','apellido','telefono');

            $output = $crud->render();
            $this->output('admin/usuarios/abm.php', $output);
        } catch (Exception $e) {
            show_error($e->getMessage() . ' --- ' . $e->getTraceAsString());
        }
        $this->load->view('admin/footer.php');
    }

    public function categories() {
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
		
        try {
            $crud = new grocery_CRUD();
			$crud->set_field_upload('photo', 'assets/uploads/files');
            $crud->set_language("spanish");
            $crud->set_theme('flexigrid');
            $crud->set_table('categories');
            $crud->set_subject('Categorias');

            $crud->display_as('name', 'Nombre');
            $crud->display_as('status', 'Estado');
			$crud->display_as('photo', 'Foto');

            $output = $crud->render();
            $this->output('admin/usuarios/abm.php', $output);
        } catch (Exception $e) {
            show_error($e->getMessage() . ' --- ' . $e->getTraceAsString());
        }
        $this->load->view('admin/footer.php');
    }
	
	public function courses() {
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
		
        try {
            $crud = new grocery_CRUD();
			$crud->set_field_upload('foto', 'assets/uploads/files');
            $crud->set_language("spanish");
            $crud->set_theme('flexigrid');
            $crud->set_table('cursos');
            $crud->set_subject('Cursos');

            $output = $crud->render();
            $this->output('admin/usuarios/abm.php', $output);
        } catch (Exception $e) {
            show_error($e->getMessage() . ' --- ' . $e->getTraceAsString());
        }
        $this->load->view('admin/footer.php');
    }

    public function subcategories() {
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
        try {
            $crud = new grocery_CRUD();
			$crud->set_field_upload('photo', 'assets/uploads/files');
            $crud->set_language("spanish");
            $crud->set_theme('flexigrid');
            $crud->set_table('subcategories');
            $crud->set_subject('Subcategorias');

            $crud->set_relation('category_id', 'categories', 'name');

            $crud->display_as('category_id', 'Categoria');
            $crud->display_as('name', 'SubCategoria');
            $crud->display_as('status', 'Estado');
			$crud->display_as('photo', 'Foto');

            $output = $crud->render();
            $this->output('admin/usuarios/abm.php', $output);
        } catch (Exception $e) {
            show_error($e->getMessage() . ' --- ' . $e->getTraceAsString());
        }
        $this->load->view('admin/footer.php');
    }

    public function modes() {
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
        try {
            $crud = new grocery_CRUD();
            $crud->set_language("spanish");
            $crud->set_theme('flexigrid');
            $crud->set_table('modes');
            $crud->set_subject('Modalidades');

            $crud->display_as('name', 'Nombre');

            $output = $crud->render();
            $this->output('admin/usuarios/abm.php', $output);
        } catch (Exception $e) {
            show_error($e->getMessage() . ' --- ' . $e->getTraceAsString());
        }
        $this->load->view('admin/footer.php');
    }

    public function currencies() {
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
        try {
            $crud = new grocery_CRUD();
            $crud->set_language("spanish");
            $crud->set_theme('flexigrid');
            $crud->set_table('currencies');
            $crud->set_subject('Monedas');

            $crud->display_as('name', 'Nombre');
            $crud->display_as('symbol', 'Simbolo');


            $output = $crud->render();
            $this->output('admin/usuarios/abm.php', $output);
        } catch (Exception $e) {
            show_error($e->getMessage() . ' --- ' . $e->getTraceAsString());
        }
        $this->load->view('admin/footer.php');
    }

    public function cities() {
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
        try {
            $crud = new grocery_CRUD();
            $crud->set_language("spanish");
            $crud->set_theme('flexigrid');
            $crud->set_table('cities');
            $crud->set_subject('Ciudades');

            $crud->display_as('country_id', 'Pais');
            $crud->display_as('name', 'Nombre');

            $crud->set_relation('country_id', 'countries', 'name');

            $output = $crud->render();
            $this->output('admin/usuarios/abm.php', $output);
        } catch (Exception $e) {
            show_error($e->getMessage() . ' --- ' . $e->getTraceAsString());
        }
        $this->load->view('admin/footer.php');
    }

    public function countries() {
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
        try {
            $crud = new grocery_CRUD();
            $crud->set_language("spanish");
            $crud->set_theme('flexigrid');
            $crud->set_table('countries');
            $crud->set_subject('Paises');

            $crud->display_as('name', 'Nombre');

            $output = $crud->render();
            $this->output('admin/usuarios/abm.php', $output);
        } catch (Exception $e) {
            show_error($e->getMessage() . ' --- ' . $e->getTraceAsString());
        }
        $this->load->view('admin/footer.php');
    }

    /**
     * Cambia el input por defecto por uno limpio
     * @return string 
     */
    public function set_password_input_to_empty() {
        return "<input type='password' name='password' value='' />";
    }

    /**
     * Cambia el input por un link a cambiar la contraseña
     * @return string 
     */
    public function change_input_to_button() {
        return '<a href="' . site_url("admin/changepassword/" . $this->uri->segment(4)) . '" class="btn" type="button">Cambiar Contraseña</a>';
    }

    /**
     * Devuelve la salida a la vista
     * @param string $view
     * @param string $output 
     */
    public function output($view, $output = null) {
        $this->load->view($view, $output);
    }

    /**
     * Accion de cambio de contraseña del usuario
     * @param int $id 
     */
    public function changePassword() {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');

        $this->form_validation->set_rules('password', 'Contraseña', 'required');
        $this->form_validation->set_rules('repassword', 'Confirmar contraseña', 'required|matches[password]');
        $this->form_validation->set_message('required', 'El campo %s es requerido');
        $this->form_validation->set_message('matches', 'El campo %s debe ser igual que el valor de la contraseña');

        if ($this->input->post()) {

            $this->load->model('user');
            $paramPassword = $this->input->post('password');
            $paramUserId = $this->input->post('id');

            if ($this->user->changePassword($this->data, $paramUserId, $paramPassword)
                    && $this->form_validation->run()) {
                redirect('admin/usuarios/edit/' . $paramUserId);
            } else {
                $this->doChangePassword($paramUserId, true);
            }
        } else {
            $this->load->view('admin/header.php');
            $this->load->view('admin/dashboard/dashboard.php', $this->data);
            $this->load->view('change-password/index.php', array('id' => $this->uri->segment(3)));
            $this->load->view('admin/footer.php');
        }
    }

    /**
     * Accion de cambio de contraseña del usuario
     * @param int $id 
     */
    public function doChangePassword($paramUserId, $pageLevelError = null) {
        $this->load->view('admin/header.php');
        $this->load->view('admin/dashboard/dashboard.php', $this->data);
        $this->load->view('change-password/index.php', array('id' => $paramUserId, 'pageLevelError' => $pageLevelError));
        $this->load->view('admin/footer.php');
    }

}

?>